from django.db import transaction

from ..exceptions import NotFoundException
from ..models.news import NewsItem
from ..repositories import BaseRepository


class NewsRepository(BaseRepository[NewsItem]):
    model_class = NewsItem # type: ignore

    def create(self, data: dict) -> NewsItem:
        return self.model_class.objects.create(**data)

    def get_by_id(self, id: int) -> NewsItem:
        try:
            return self.model_class.objects.get(pk=id)
        except self.model_class.DoesNotExist:
            raise NotFoundException("News item not found")

    def update(self, id: int, data: dict) -> NewsItem:
        with transaction.atomic():
            news = self.get_by_id(id)
            for key, value in data.items():
                setattr(news, key, value)
            news.save()
            return news

    def delete(self, id: int) -> bool:
        count, _ = self.model_class.objects.filter(pk=id).delete()
        return count > 0